package com.aliware.tianchi;

import com.aliware.tianchi.common.TianchiRpcContants;
import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

/**
 * @author daofeng.xjf
 * <p>
 * 服务端过滤器
 * 可选接口
 * 用户可以在服务端拦截请求和响应,捕获 rpc 调用时产生、服务端返回的已知异常。
 */
@Activate(group = Constants.PROVIDER)
public class TestServerFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try {
            //获取dubbo服务的线程数
            String threads = invoker.getUrl().getParameter(Constants.THREADS_KEY);
            if(threads!=null&&ProviderContext.getInstance().getThreads()==null){
                ProviderContext.getInstance().setThreads(threads);
            }
            //获取gateway传递的获取线程数信号
            String ackThreads = RpcContext.getContext().getAttachment(TianchiRpcContants.ACK_THREADS);
            if(ackThreads!=null){
                //当获取到了线程数，将发送给gateway
                ProviderContext.getInstance().sendThreads(ackThreads);
            }
            Result result = invoker.invoke(invocation);
            return result;
        } catch (Exception e) {
            throw e;
        }
    }


}
